﻿@*
    采购单 新增/编辑对话框
*@
@using System.Collections.ObjectModel
@inject DialogService DialogService
@inject IProductService ProductService
@inject IBuyOrderService BuyOrderService
@inject ISupplierService SupplierService

<RadzenStack Gap="1rem">
    <RadzenTemplateForm EditContext="editContext" TItem="BuyOrder" Data="@model" Submit=@OnSubmit>
    <RadzenStack Style="display:flex" class="rz-p-0" 
                 Orientation="Orientation.Vertical" 
                 AlignItems="AlignItems.Normal"
                 JustifyContent="JustifyContent.SpaceBetween">
        <RadzenCard class="rz-my-6">
            <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Start" Wrap="FlexWrap.Wrap">
                <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                    单据日期
                    <RadzenDatePicker @bind-Value="@model!.CreatedAt" DateFormat="yyyy-MM-dd"/>
                </RadzenStack>
                 <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                    客户名称
                    <RadzenDropDown @bind-Value=@model.SupplierId
                                    Data=@Suppliers
                                    Change="OnDropdownChange"
                                    TextProperty="Name"
                                    ValueProperty="Id"
                                    Style="width: 100%;" 
                                    Name="DropDownBindValue" />
                </RadzenStack>
                <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                    订单编号
                    <RadzenTextBox @bind-Value="@model!.Code" Style="width: 100%"/>
                </RadzenStack>
                <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                    订单标题
                    <RadzenTextBox @bind-Value="@model!.Name" Style="width: 100%"/>
                </RadzenStack>
                <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                    备注
                    <RadzenTextBox @bind-Value="@model!.Remark" Style="width: 100%;" />
                </RadzenStack>
            </RadzenStack>
        </RadzenCard>
        <RadzenStack Orientation="Orientation.Horizontal">
            <RadzenDataGrid Style="flex:1; height:60vh"
                            EmptyText="暂无数据"
                            Data="@model.Details"
                            GridLines="Radzen.DataGridGridLines.Default"
                            AllowPaging="true"
                            AllowSorting="true">
                <Columns>
                    <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
                    <RadzenDataGridColumn Property="" Title="操作">
                        <Template Context="data">
                            <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                                <RadzenButton Text="删除" @onclick:stopPropagation Click="@(args => Delete(data))" ButtonStyle="ButtonStyle.Danger" />
                            </RadzenStack>
                        </Template>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Property="ProductCode" Title="代码" />
                    <RadzenDataGridColumn Property="ProductName" Title="名称" />
                    <RadzenDataGridColumn Property="UnitPrice" Title="名称" />
                    <RadzenDataGridColumn Title="数量">
                        <Template Context="data">
                            <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                                <RadzenNumeric @bind-Value="data.Quantity" Min="0" Max="10000" Style="width: 100px;" />
                            </RadzenStack>
                        </Template>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Property="TotalPrice" Title="总价" />
                    <RadzenDataGridColumn Property="Remark" Title="备注" />
                </Columns>
            </RadzenDataGrid>
            <RadzenDataGrid Style="flex:1; height:60vh" 
                            EmptyText="暂无数据" 
                            Data="@Products"
                            GridLines="Radzen.DataGridGridLines.Default"
                            AllowPaging="true" 
                            AllowSorting="true">
                <Columns>
                    <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
                    <RadzenDataGridColumn Property="" Title="操作">
                        <Template Context="data">
                            <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                                <RadzenButton Text="左移" @onclick:stopPropagation Click="@(args => Add(data))" ButtonStyle="ButtonStyle.Danger" />
                            </RadzenStack>
                        </Template>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Property="Name" Title="产品名称" />
                    <RadzenDataGridColumn Property="Unit" Title="产品单位" />
                    <RadzenDataGridColumn Property="Remark" Title="备注" />
                </Columns>
            </RadzenDataGrid>
        </RadzenStack>
    </RadzenStack>

    <RadzenStack Gap="1rem" Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.End" Style="height: 20%;">
        <RadzenButton ButtonStyle="ButtonStyle.Secondary" Text="取消" Click="OnCancel" />
        <RadzenButton ButtonStyle="ButtonStyle.Primary" Text="保存" ButtonType="ButtonType.Submit" />
    </RadzenStack>
   </RadzenTemplateForm>
</RadzenStack>

@code {
    [Parameter]
    public BuyOrder POrder { get; set; } = default!;
    private ObservableCollection<ProductDto> Products { get; set; } = default!;
    private List<SupplierDto> Suppliers { get; set; } = default!;
    private EditContext? editContext;
    private BuyOrder model = default!;

    /// <summary>
    /// Debug
    /// </summary>
    /// <param name="value"></param>
    void OnDropdownChange(object value)
    {
        Console.WriteLine($"Selected Customer: {value}");
    }

    private async Task Delete(BuyOrderDetail detail)
    {
        try
        {
            // 1.订单移除选中的商品
            model.Details.Remove(detail);

            // 2. 商品列表增加上商品
            var product = await ProductService.Get(detail.ProductId);
            if (product == null)
                throw new Exception("产品不存在，无法删除。");
            Products.Add(product);
        }
        catch (Exception e)
        {
            await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
        }
    }

    private void Add(ProductDto selectedItem)
    {
        // 构造新商品
        var detail = new BuyOrderDetail
        {
            ProductId = selectedItem.Id,
            Quantity = 1, // 默认数量为1，可以根据需要调整
            UnitPrice = selectedItem.Price,
            Remark = selectedItem.Remark // 可以根据需要设置备注
        };

        // 订单增加商品
        model!.Details.Add(detail);
        
        // 商品列表减少商品
        Products.Remove(selectedItem);
    }

    private void OnCancel()
    {
        DialogService.Close(null);
    }

    void OnSubmit()
    {
        try
        {           
            var result = BuyOrderService.Save(model);
            DialogService.Close(result);
        }
        catch (Exception e)
        {
            DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
        }
    }

    protected override async void OnInitialized()
    {
        base.OnInitialized();

        // 构造上下文数据
        model = POrder;
        editContext = new EditContext(model!);

        // 初始化产品列表
        var products = await ProductService.Search();
        var subSet = products.Where(p => model.Details.All(d => d.ProductId != p.Id)).ToList();
        Products = new ObservableCollection<ProductDto>(subSet);

        // 获取客户列表
        Suppliers = await SupplierService.Search();

        // 如果没有选择客户，则第一个客户做默认值
        if (model.SupplierId == 0)
        {
            model.SupplierId = Suppliers.First().Id;
        }
    }
}